# -*- coding: utf-8 -*-
"""
I AM HOLLOW Plugin
 - 简洁的滚动区域界面
 - 设定摸鱼分钟数（0 表示直到手动停止）
 - 开始按钮：每分钟随机移动一次鼠标
 - 终止按钮：停止并显示本次摸鱼时长

注意：严格避免在线程里调用主界面控件。这里使用 QTimer 在主线程驱动逻辑。
"""

import random
import traceback
from datetime import datetime

from PySide6.QtWidgets import (
    QWidget, QVBoxLayout, QHBoxLayout, QLabel, QPushButton,
    QScrollArea, QFrame, QSpinBox, QGroupBox, QTextEdit
)
from PySide6.QtCore import Qt, QTimer
from PySide6.QtGui import QCursor, QGuiApplication, QFont
import pyautogui

from core.plugin_base import PluginBase


class Plugin(PluginBase):
    """I AM HOLLOW 插件主类"""

    # 插件元信息
    NAME = "i_am_hollow"
    DISPLAY_NAME = "I am hollow"
    DESCRIPTION = "You may see me, but I am hollow. -- Detachment(2011)"
    VERSION = "1.0.0"
    AUTHOR = "HSBC IT Support"

    def __init__(self, app=None):
        super().__init__(app)

        # 运行状态
        self._timer: QTimer | None = None
        self._start_time: datetime | None = None
        self._end_time: datetime | None = None
        
        # 鼠标移动配置
        self._max_move_distance = 300  # 最大移动距离
        self._enable_natural_movement = True  # 启用自然移动模式
        self._add_random_jitter = True  # 添加随机抖动

        # UI 控件引用（用于更新状态文本）
        self._status_label: QLabel | None = None
        self._duration_spin: QSpinBox | None = None
        self._start_btn: QPushButton | None = None
        self._stop_btn: QPushButton | None = None
        self._log_text: QTextEdit | None = None
        self._title_label: QLabel | None = None
        self._desc_label: QLabel | None = None

    def initialize(self) -> bool:
        """初始化插件"""
        self.log_info("🚀 初始化 I_AM_HOLLOW 插件")
        return True

    def create_widget(self) -> QWidget:
        """创建插件界面：现代化UI设计"""
        # 容器框架
        frame = QFrame()
        frame_layout = QVBoxLayout(frame)
        frame_layout.setContentsMargins(20, 20, 20, 20)
        frame_layout.setSpacing(15)

        # 标题 - 现代化样式
        self._title_label = QLabel(self.tr("plugin.i_am_hollow.title"))
        title_font = QFont()
        title_font.setPointSize(18)
        title_font.setBold(True)
        self._title_label.setFont(title_font)
        self._title_label.setAlignment(Qt.AlignCenter)
        frame_layout.addWidget(self._title_label)

        # 描述信息 - 卡片式设计
        self._desc_label = QLabel(self.tr("plugin.i_am_hollow.description"))
        self._desc_label.setWordWrap(True)
        self._desc_label.setStyleSheet(
            "QLabel {"
            "    background-color: #f8f9fa;"
            "    border: 1px solid #dee2e6;"
            "    border-radius: 8px;"
            "    padding: 15px;"
            "    color: #495057;"
            "    font-size: 13px;"
            "}"
        )
        frame_layout.addWidget(self._desc_label)

        # 功能区域 - 使用QGroupBox
        function_group = QGroupBox(self.tr("plugin.i_am_hollow.function_group"))
        function_group.setStyleSheet("""
            QGroupBox {
                font-weight: bold;
                border: 2px solid #3498db;
                border-radius: 5px;
                margin-top: 10px;
                padding-top: 10px;
            }
            QGroupBox::title {
                subcontrol-origin: margin;
                left: 10px;
                padding: 0 5px 0 5px;
            }
        """)
        function_layout = QVBoxLayout(function_group)

        # 输入区域 - 设定分钟数
        input_row = QHBoxLayout()
        input_label = QLabel(self.tr("plugin.i_am_hollow.input.label"))
        input_label.setStyleSheet("font-weight: bold;")
        self._duration_spin = QSpinBox()
        self._duration_spin.setRange(0, 720)  # 0 表示持续到手动停止，720=12小时上限
        self._duration_spin.setValue(0)
        self._duration_spin.setSuffix(self.tr("plugin.i_am_hollow.input.suffix"))
        self._duration_spin.setStyleSheet(
            "QSpinBox {"
            "    padding: 5px;"
            "    border: 1px solid #ced4da;"
            "    border-radius: 4px;"
            "    font-size: 13px;"
            "}"
        )
        input_row.addWidget(input_label)
        input_row.addWidget(self._duration_spin)
        input_row.addStretch()
        function_layout.addLayout(input_row)

        # 控制按钮区域
        btn_row = QHBoxLayout()
        self._start_btn = QPushButton(self.tr("plugin.i_am_hollow.start"))
        self._stop_btn = QPushButton(self.tr("plugin.i_am_hollow.stop"))
        self._stop_btn.setEnabled(False)
        
        # 开始按钮样式
        self._start_btn.setStyleSheet(
            "QPushButton {"
            "    background-color: #28a745;"
            "    color: white;"
            "    border: none;"
            "    padding: 10px 20px;"
            "    border-radius: 6px;"
            "    font-weight: bold;"
            "    font-size: 14px;"
            "}"
            "QPushButton:hover {"
            "    background-color: #218838;"
            "}"
            "QPushButton:pressed {"
            "    background-color: #1e7e34;"
            "}"
            "QPushButton:disabled {"
            "    background-color: #6c757d;"
            "    color: #dee2e6;"
            "}"
        )
        
        # 停止按钮样式
        self._stop_btn.setStyleSheet(
            "QPushButton {"
            "    background-color: #dc3545;"
            "    color: white;"
            "    border: none;"
            "    padding: 10px 20px;"
            "    border-radius: 6px;"
            "    font-weight: bold;"
            "    font-size: 14px;"
            "}"
            "QPushButton:hover {"
            "    background-color: #c82333;"
            "}"
            "QPushButton:pressed {"
            "    background-color: #bd2130;"
            "}"
            "QPushButton:disabled {"
            "    background-color: #6c757d;"
            "    color: #dee2e6;"
            "}"
        )
        
        self._start_btn.clicked.connect(self._on_start_clicked)
        self._stop_btn.clicked.connect(self._on_stop_clicked)
        btn_row.addWidget(self._start_btn)
        btn_row.addWidget(self._stop_btn)
        btn_row.addStretch()
        function_layout.addLayout(btn_row)

        frame_layout.addWidget(function_group)

        # 状态显示区域
        status_group = QGroupBox(self.tr("plugin.i_am_hollow.status_group"))
        status_group.setStyleSheet("""
            QGroupBox {
                font-weight: bold;
                border: 2px solid #27ae60;
                border-radius: 5px;
                margin-top: 10px;
                padding-top: 10px;
            }
            QGroupBox::title {
                subcontrol-origin: margin;
                left: 10px;
                padding: 0 5px 0 5px;
            }
        """)
        status_layout = QVBoxLayout(status_group)
        
        self._status_label = QLabel(self.tr("plugin.i_am_hollow.status.idle"))
        self._status_label.setWordWrap(True)
        self._status_label.setStyleSheet(
            "QLabel {"
            "    background-color: #e9ecef;"
            "    border: 1px solid #ced4da;"
            "    border-radius: 6px;"
            "    padding: 12px;"
            "    font-weight: bold;"
            "    color: #495057;"
            "}"
        )
        status_layout.addWidget(self._status_label)
        frame_layout.addWidget(status_group)

        # 日志显示区域
        log_group = QGroupBox(self.tr("plugin.i_am_hollow.log_group"))
        log_group.setStyleSheet("""
            QGroupBox {
                font-weight: bold;
                border: 2px solid #e67e22;
                border-radius: 5px;
                margin-top: 10px;
                padding-top: 10px;
            }
            QGroupBox::title {
                subcontrol-origin: margin;
                left: 10px;
                padding: 0 5px 0 5px;
            }
        """)
        log_layout = QVBoxLayout(log_group)
        
        self._log_text = QTextEdit()
        self._log_text.setMaximumHeight(120)
        self._log_text.setReadOnly(True)
        self._log_text.setStyleSheet(
            "QTextEdit {"
            "    background-color: #f8f9fa;"
            "    border: 1px solid #dee2e6;"
            "    border-radius: 6px;"
            "    font-family: 'Consolas', 'Monaco', monospace;"
            "    font-size: 11px;"
            "    color: #495057;"
            "}"
        )
        
        # 添加初始日志
        self._log_text.append(f"[{datetime.now().strftime('%H:%M:%S')}] [INFO] Plugin initialized successfully.")
        self._log_text.append(f"[{datetime.now().strftime('%H:%M:%S')}] [INFO] Ready to start hollow mode.")
        
        log_layout.addWidget(self._log_text)
        frame_layout.addWidget(log_group)

        # 添加弹性空间
        frame_layout.addStretch()

        # 连接信号
        self._start_btn.clicked.connect(self._on_start_clicked)
        self._stop_btn.clicked.connect(self._on_stop_clicked)

        # 滚动区域包装
        scroll = QScrollArea()
        scroll.setWidgetResizable(True)
        scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        scroll.setWidget(frame)

        container = QWidget()
        layout = QVBoxLayout(container)
        layout.addWidget(scroll)
        return container

    def cleanup(self) -> None:
        """清理资源：停止计时器，清空状态"""
        try:
            if self._timer:
                self._timer.stop()
                self._timer.deleteLater()
                self._timer = None
            self._start_time = None
            self._end_time = None
            self.log_info("🧹 清理完成")
        except Exception as e:
            self.log_error(f"❌ 清理失败: {e}")

    # -------------------- 事件逻辑 -------------------- #
    def _on_start_clicked(self):
        """开始摸鱼模式（使用 QTimer，避免线程操作 UI）"""
        if self._timer and self._timer.isActive():
            return

        minutes = int(self._duration_spin.value()) if self._duration_spin else 0
        self._start_time = datetime.now()
        self._end_time = None

        # 每分钟触发一次鼠标移动
        self._timer = QTimer(self)
        self._timer.timeout.connect(self._move_mouse_random)
        self._timer.start(60_000)  # 60 秒

        # 根据时长设置自动停止（如果 minutes>0）
        if minutes > 0:
            # 使用额外的单次计时器在主线程中停止
            stop_timer = QTimer(self)
            stop_timer.setSingleShot(True)
            stop_timer.timeout.connect(self._on_stop_clicked)
            stop_timer.start(minutes * 60_000)

        # UI状态
        if self._status_label:
            if minutes > 0:
                self._status_label.setText(self.tr("plugin.i_am_hollow.status.running_limited", minutes=minutes))
            else:
                self._status_label.setText(self.tr("plugin.i_am_hollow.status.running"))

        if self._start_btn:
            self._start_btn.setEnabled(False)
        if self._stop_btn:
            self._stop_btn.setEnabled(True)

        # 状态栏提示
        if minutes > 0:
            self.show_status_message(self.tr("plugin.i_am_hollow.toast.started_limited", minutes=minutes))
        else:
            self.show_status_message(self.tr("plugin.i_am_hollow.toast.started"))

        # 日志记录
        if self._log_text:
            if minutes > 0:
                self._log_text.append(f"[INFO] Hollow mode started with {minutes} minutes limit.")
            else:
                self._log_text.append("[INFO] Hollow mode started (unlimited).")

        self.log_info("🔄 Hollow mode started")

        # 立即移动一次以确认效果（避免等待1分钟）
        self._move_mouse_random()
        
        # 记录鼠标移动日志
        if self._log_text:
            self._log_text.append("[INFO] Initial mouse movement completed.")

    def _on_stop_clicked(self):
        """停止摸鱼模式"""
        if self._timer:
            self._timer.stop()
            self._timer.deleteLater()
            self._timer = None

        if self._start_time:
            self._end_time = datetime.now()
            elapsed_sec = int((self._end_time - self._start_time).total_seconds())
            minutes = elapsed_sec // 60
            seconds = elapsed_sec % 60
            if self._status_label:
                self._status_label.setText(
                    self.tr("plugin.i_am_hollow.status.stopped", minutes=minutes, seconds=seconds)
                )
            self.show_status_message(self.tr("plugin.i_am_hollow.toast.stopped"))
            
            # 日志记录
            if self._log_text:
                self._log_text.append(f"[INFO] Hollow mode stopped. Duration: {minutes}m {seconds}s")
            
            self.log_info(f"✅ Hollow mode stopped, duration: {minutes}m {seconds}s")
        else:
            if self._status_label:
                self._status_label.setText(self.tr("plugin.i_am_hollow.status.idle"))

        if self._start_btn:
            self._start_btn.setEnabled(True)
        if self._stop_btn:
            self._stop_btn.setEnabled(False)

        self._start_time = None
        self._end_time = None

    # -------------------- 行为逻辑 -------------------- #
    def _move_mouse_random(self):
        """随机移动鼠标到屏幕可用区域，使用平滑轨迹移动"""
        try:
            if not self._enable_natural_movement:
                # 回退到简单的随机移动
                screen = QGuiApplication.primaryScreen()
                if not screen:
                    return
                geom = screen.availableGeometry()
                x = random.randint(geom.left(), geom.right())
                y = random.randint(geom.top(), geom.bottom())
                pyautogui.moveTo(x, y)
                if self._log_text:
                    current_time = datetime.now().strftime("%H:%M:%S")
                    self._log_text.append(f"[{current_time}] Simple mouse move to ({x}, {y})")
                return
            
            screen = QGuiApplication.primaryScreen()
            if not screen:
                return
            geom = screen.availableGeometry()
            
            # 获取当前鼠标位置
            current_pos = pyautogui.position()
            
            # 在可用区域内随机生成目标位置，但不要太远（模拟人类行为）
            min_x = max(geom.left(), current_pos.x - self._max_move_distance)
            max_x = min(geom.right(), current_pos.x + self._max_move_distance)
            min_y = max(geom.top(), current_pos.y - self._max_move_distance)
            max_y = min(geom.bottom(), current_pos.y + self._max_move_distance)
            
            target_x = random.randint(int(min_x), int(max_x))
            target_y = random.randint(int(min_y), int(max_y))
            
            # 随机选择移动类型，模拟不同的用户行为
            move_types = [
                (pyautogui.easeInOutQuad, 0.8, 1.2),      # 平滑移动
                (pyautogui.easeOutQuad, 0.5, 1.0),        # 快速开始慢速结束
                (pyautogui.easeInQuad, 1.0, 1.5),         # 慢速开始快速结束
                (pyautogui.linear, 0.3, 0.7),             # 线性移动（快速）
            ]
            
            tween_func, min_duration, max_duration = random.choice(move_types)
            duration = random.uniform(min_duration, max_duration)
            
            # 使用pyautogui的平滑移动功能
            pyautogui.moveTo(target_x, target_y, duration=duration, tween=tween_func)
            
            # 随机添加小幅度抖动（模拟人类手部微小移动）
            if self._add_random_jitter and random.random() < 0.3:  # 30%概率添加微小抖动
                jitter_x = random.randint(-5, 5)
                jitter_y = random.randint(-5, 5)
                pyautogui.moveRel(jitter_x, jitter_y, duration=0.1)
            
            self.log_debug(f"🐭 Smoothly moved cursor from ({current_pos.x}, {current_pos.y}) to ({target_x}, {target_y})")
            
            # 记录鼠标移动日志
            if self._log_text:
                current_time = datetime.now().strftime("%H:%M:%S")
                move_type = "smooth" if duration > 0.8 else "quick"
                self._log_text.append(f"[{current_time}] {move_type.capitalize()} mouse movement: ({current_pos.x}, {current_pos.y}) → ({target_x}, {target_y})")
                
        except Exception as e:
            self.log_error(f"❌ Failed to move cursor: {e} - {traceback.format_exc()}")